rm(list = ls())

library(tidyverse)
scr1 <- list.files("/Pub/Users/wangyk/Project_wangyk/Codelib_YK/some_scr", full.names = T, recursive = T, pattern = "\\.R$")
scr2 <- list.files("/Pub/Users/wangyk/Project_wangyk/Codelib_YK/CY_code", recursive = T, full.names = T, pattern = "\\.R$")
walk(c(scr2, scr1), ~ source(.x))
# library(YK.pkg)

source("/Pub/Users/wangyk/Project_wangyk/Codelib_YK/some_cancers/major_test2.r")

out_home <- "/Pub/Users/wangyk/project/Poroject/F210823005_非小细胞肺癌血小板/"

coef_file <- list.files(out_home, recursive = T, full.names = T)[list.files(out_home, recursive = T, full.names = T) %>%
    str_detect("coef_file") %>%
    which()] %>%
    read_delim() %>%
    as.data.frame()

RData <- list.files(out_home, recursive = TRUE, full.names = TRUE, pattern = "\\.RData$")
for (i in 1:length(RData)) {
    load(RData[i], verbose = TRUE)
}


load("/Pub/Data/Data_Center/TCGA/TCGA-LUAD/data_CNV_Gene.RData")
load("/Pub/Users/cuiye/database/gene_map.RData")
data_CNV_Gene <- data_CNV_Gene %>%
    select(-c(2, 3)) %>%
    rename(id = 1) %>%
    mutate(id = substr(id, 1, 15))
cnv_exp <- data_CNV_Gene %>% inner_join(gene_map %>% dplyr::select(id,gene_name),.)
cnv_exp <- exp_martix_aggregate(input_exp = cnv_exp %>% dplyr::select(-id), rownames_type = "gene_name", fun = "delete")
colnames(cnv_exp) <- str_sub(colnames(cnv_exp),1,16)
luad_cnv <- cnv_exp

load("/Pub/Data/Data_Center/TCGA/TCGA-LUSC/data_CNV_Gene.RData")
load("/Pub/Users/cuiye/database/gene_map.RData")
data_CNV_Gene <- data_CNV_Gene %>%
    select(-c(2, 3)) %>%
    rename(id = 1) %>%
    mutate(id = substr(id, 1, 15))
cnv_exp <- data_CNV_Gene %>% inner_join(gene_map %>% dplyr::select(id,gene_name),.)
cnv_exp <- exp_martix_aggregate(input_exp = cnv_exp %>% dplyr::select(-id), rownames_type = "gene_name", fun = "delete")
colnames(cnv_exp) <- str_sub(colnames(cnv_exp),1,16)
LUSC_cnv <- cnv_exp

cnv_exprs <- dplyr::inner_join(
    luad_cnv %>% rownames_to_column("gene"),
    LUSC_cnv %>% rownames_to_column("gene")
)

write_tsv(x = cnv_exprs,file = file.path(out_home,'out/NSCLC_CNV.tsv'))


cnv_exprs <- cnv_exprs[, -{
    cnv_exprs %>%
        colnames() %>%
        endsWith("1") %>%
        which()
}]

colnames(cnv_exprs)

file.copy(
    "/Pub/Users/liulk/Project/1.F211201005_消化系统泛癌分析揭示乳酸代谢在肿瘤中的调控和临床结局/scr/1.3.CNV_Mutation.r",
    file.path(out_home, "runtime/src/llk_cnv_oncoplot.r")
)


### 加载包
library(tidyverse)
library(ComplexHeatmap)
library(circlize)
library(do)

cancer_data <- cnv_exprs %>%
    filter(gene %in% xgene) %>%
    column_to_rownames("gene") %>%
    t() %>%
    as.data.frame()

cnv_mutation <- Replace(data = cancer_data, from = -1, to = "Deep_deletion")
cnv_mutation <- Replace(data = cnv_mutation, from = 1, to = "Amplification")
cnv_mutation <- Replace(data = cnv_mutation, from = 0, to = "No_change")

data <- cnv_mutation %>%
    t() %>%
    as.data.frame()

cnv_num_in_xgene <- map_df(rownames(data), function(x) {
    # x <- 'THBD'
    data[x, ] %>%
        as.character() %>%
        table() %>%
        as.data.frame() %>%
        rename(type = 1) %>%
        column_to_rownames("type") %>%
        t() %>%
        as.data.frame() %>%
        add_column('gene' = x)
})

cnv_num_in_xgene <- remove_rownames(cnv_num_in_xgene) %>% arrange(No_change)

xlsx::write.xlsx(x = cnv_num_in_xgene,file = file.path(out_home,'out/cnv_num_in_xgene.xlsx'))


top_cnv_gene <- head(cnv_num_in_xgene,20) %>% pull(gene)

col <- c(
    "Amplification" = RColorBrewer::brewer.pal(8, "Paired")[2],
    "Deep_deletion" = RColorBrewer::brewer.pal(8, "Paired")[6]
)


alter_fun <- list(
    background = function(x, y, w, h) {
        grid.rect(x, y, w - unit(0.5, "mm"), h - unit(0.5, "mm"),
            gp = gpar(fill = "#CCCCCC", col = NA)
        )
    },
    Amplification = function(x, y, w, h) {
        grid.rect(x, y, w - unit(0.5, "mm"), h - unit(0.5, "mm"),
            gp = gpar(fill = col["Amplification"], col = NA)
        )
    },
    Deep_deletion = function(x, y, w, h) {
        grid.rect(x, y, w - unit(0.5, "mm"), h - unit(0.5, "mm"),
            gp = gpar(fill = col["Deep_deletion"], col = NA)
        )
    }
)

# column_title <- paste0("Copy number variation of ", x)
heatmap_legend_param <- list(
    title = "Alternations", at = c("Amplification", "Deep_deletion"),
    labels = c("Amplification", "Deep_deletion")
)

data <- Replace(data = data,'No_change','')

p3 <- oncoPrint(data[top_cnv_gene,],
    alter_fun = alter_fun, col = col,
    # column_title = column_title,
    remove_empty_columns = TRUE,
    remove_empty_rows = TRUE,
    heatmap_legend_param = heatmap_legend_param
)
p4 <- ggplotify::as.ggplot(p3)
plotout(od = file.path(out_home,'out/cnv/'), name = 'tcga_xgene', w = 7, h = 6, p = p3)




top_cnv_type <- cnv_mutation[, top_cnv_gene] %>%
    rownames_to_column("sample") %>%
    pivot_longer(cols = -sample, values_to = "cnv", names_to = "gene") %>% 
    mutate(sample = substr(sample,1,15))

top_cnv_type_exprs <- train_data$tumor_exprs[top_cnv_gene, ] %>%
    t() %>%
    as.data.frame() %>%
    rownames_to_column("sample") %>%
    pivot_longer(cols = -sample, values_to = "exprs", names_to = "gene") 

top_cnv_type_exprs <- inner_join(top_cnv_type,top_cnv_type_exprs)


library(ggpubr)

p_list <- map(unique(top_cnv_type_exprs$gene), function(x) {
    p <- top_cnv_type_exprs %>%
        filter(gene == x) %>%
        ggplot(aes(x = cnv, y = exprs, fill = cnv)) +
        geom_boxplot(alpha = .9, outlier.size = .5, width = .55) +
        scale_fill_manual(values = color1) +
        theme_pubr(13) +
        labs(subtitle = str_glue("{x} Expression"),fill = 'CNV') +
        theme(
            axis.title.y.left = element_blank(), 
            axis.text.x.bottom = element_blank(),
            axis.title.x.bottom = element_blank(),
            axis.ticks.x.bottom = element_blank()
        )+
        stat_compare_means(aes(label = ..p.signif..))

    return(p)
})

p <- ggarrange(plotlist = p_list, common.legend = T, nrow = 4, ncol = 5, align = "hv") +
    theme(plot.margin = unit(c(.2, .2, .2, .2), "cm"))

plotout(p = p, od = file.path(out_home, "/out/cnv/"), name = "cnv_exprs", w = 12, h = 12)


cnv <- data.table::fread(file.path(out_home,'out/NSCLC_CNV.tsv'))  %>% as.data.frame() %>% rename(Gene = gene)

top_cnv_gene <- c(
    "KCNMB2", "KCNMB3", "MFN1", "AHSG", "HRG", "OPA1", "GP5", "KIFC2", "LPCAT1",
    "TIPARP", "ITGA10", "TXNIP", "SLA", "TACC1", "P2RY12", "SNTB1", "CTSS", "PROS1", "PLOD2", "MRPL13"
)
cnv <- cnv %>% filter(Gene %in% top_cnv_gene)

a <- CNV_Freq_Dumbbell_Chart(
    CNV_df = cnv, gene_col = "Gene", od = file.path(out_home, "out/cnv/"),
    var_name = "tcga_top20",
    w = 3, h = 6, h_plot  = F
)

